package com.fox0g.filter;
import org.springframework.stereotype.Service;


//算术平均滤波器
@Service
//public class ArithmeticMeanFilter {
//    private int[] buffer;
//    private int bufferIndex;
//    private int bufferSum;
//
//    public ArithmeticMeanFilter(int bufferSize) {
//        this.buffer = new int[bufferSize];
//        this.bufferIndex = 0;
//        this.bufferSum = 0;
//    }
//
//    public int filter(int newValue) {
//        // 从缓冲区中移除旧值
//        int oldValue = buffer[bufferIndex];
//        bufferSum -= oldValue;
//
//        // 将新值加入缓冲区
//        buffer[bufferIndex] = newValue;
//        bufferSum += newValue;
//
//        // 更新缓冲区索引
//        bufferIndex = (bufferIndex + 1) % buffer.length;
//
//        // 计算并返回平均值
//        return bufferSum / buffer.length;
//    }
//}

public class ArithmeticMeanFilter {
    private double[] buffer;
    private int bufferIndex;
    private double bufferSum;

//    public ArithmeticMeanFilter(int bufferSize) {
//        this.buffer = new double[bufferSize];
//        this.bufferIndex = 0;
//        this.bufferSum = 0.0;
//    }


    public ArithmeticMeanFilter() {
        this.buffer = new double[5];
        this.bufferIndex = 0;
        this.bufferSum = 0.0;
    }

    public double filter(double newValue) {
        // 从缓冲区中移除旧值
        double oldValue = buffer[bufferIndex];
        bufferSum -= oldValue;

        // 将新值加入缓冲区
        buffer[bufferIndex] = newValue;
        bufferSum += newValue;

        // 更新缓冲区索引
        bufferIndex = (bufferIndex + 1) % buffer.length;

        // 计算并返回平均值
        return bufferSum / buffer.length;
    }
}